<?php

namespace app\common\service;

use app\common\Constants;
use app\common\exception\BusinessException;
use think\captcha\facade\Captcha;
use think\facade\Cache;

class CaptchaService
{
    public static function getCaptcha()
    {
        // 生成随机数
        $key = uniqid((string)rand(00000, 99999), true);
        // 生成验证码
        $result = Captcha::create();
        // base64 图片
        $base64_image = "data:image/png;base64," . base64_encode($result->getData());
        // 获取生成的验证码的hash值
        $captcha = session('captcha.key');
        // 缓存缓存验证码Hash值到缓存，并限定有效期
        $cacheKey = Constants::ADMIN_CAPTCHA_KEY_PREFIX . $key;
        Cache::set($cacheKey, $captcha, config('rds.captcha_expired'));
        // 组织数据
        $data = ['captchaKey' => $key, 'captchaBase64' => $base64_image];
        return $data;
    }

    public static function checkCaptcha($data): void
    {
        $cacheKey = Constants::ADMIN_CAPTCHA_KEY_PREFIX . $data['captchaKey'];
        if (Cache::has($cacheKey)) {
            $value = Cache::get($cacheKey);
            // 验证码验证
            if ($value && password_verify(mb_strtolower($data['captchaCode'], 'UTF-8'), $value)) {
                // 校验成功后，删除验证码
                Cache::delete($cacheKey);
            } else {
                // 验证码不匹配
                throw new BusinessException(Constants::E_AUTH_VERIFICATION_CODE_NOT_MATCH);
            }
        } else {
            throw new BusinessException(Constants::E_AUTH_VERIFICATION_CODE_EXPIRED);
        }
    }
}